<?php

/*
 * Elaborado Por: Ebrain Cedeno
 */

include 'include.php';

extract($_SERVER);

if (isset($REQUEST_URI) and strlen($REQUEST_URI) > 1){
    $url_value = explode("/",substr($REQUEST_URI,1));
    
    if ($indice = array_search("index.php", $url_value)){
	if ($indice > 0){
                $temp_url_value = $url_value;
                $url_value = array();
                foreach ($temp_url_value as $llave=>$parameter){
                        if ($llave >= $indice){ 
                                $url_value[]=$parameter;
                        }
                }
        }

    }
    elseif ($indice = array_search("",$url_value)){
	if ($indice > 0){
		$temp_url_value = $url_value;
		$url_value = array();
		foreach ($temp_url_value as $llave=>$parameter){
			if ($llave >= $indice){
				$url_value[]=$parameter;
			}
		}
	}
	
    }
    
    if (isset($url_value[1])){
        if (file_exists('view/'.strtolower($url_value[1]))){
        
            //cargando el controlador de la vista
        
            if (stripos($url_value[2], "?")){ //si vienen parametros get los quitamos para cargar el controlador indicado
                $valor = explode("?",$url_value[2]);
                $url_value[2] = $valor[0];
            }
            
            $name_class = ucfirst($url_value[1])."Controller";
            $module_selected = new $name_class;
            $method_name = "Control".ucfirst($url_value[2]);
            if ($url_value[2] == ""){
                $url_value[2] = "index";
            }
            if (method_exists($module_selected, $method_name)){
                $module_selected->$method_name();
            }
            
            if (isset($url_value[2])){
                if (file_exists('view/'.$url_value[1]."/".$url_value[2].".php")){ // si existe la vista la cargamos si no cargamos la vista de not found
                    $module_selected->render('view/'.$url_value[1]."/".$url_value[2].".php");
                }
                else{
                    $module_selected->render('internal/error/view_not_found.php');
                }
            }
            else{
                $module_selected->render('view/'.$url_value[1]."/index.php");
            }
        }
        else{
            
            die("No se pudo encontrar la vista solicitada (recuerda mejoraar esto cuando agreges el manejo de plantillas)");
        }
    }
    else{
        $class_name = ucfirst($config['default_module']).'Controller';
        $module_default = new $class_name;
        $module_default->ControlIndex();
        $module_default->render('view/'.$config['default_module'].'/index.php');
    }
}
else{
    
    $class_name = ucfirst($config['default_module']).'Controller';
    $module_default = new $class_name;
    $module_default->ControlIndex();
    $module_default->render('view/'.$config['default_module'].'/index.php');
}